import axios from "axios";
import { Message } from "element-ui";
import router from "@router/index";
import apis from "./apis";

axios.defaults.timeout = 10000;
axios.defaults.baseURL = apis.host;
axios.interceptors.request.use(
	(config) => {
		// 拦截地址，并且重定义地址
		let token = localStorage.getItem("token");
		if (token) {
			config.headers["Authorization"] = "Bearer " + token;
		}
		if (!config.headers["Content-Type"]) {
			config.headers["Content-Type"] = "application/json";
		}
		if (apis[config.url]) {
			config.url = apis[config.url];
		}
		if (!config.data) {
			config.data = {};
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);
axios.interceptors.response.use(
	(response) => {
		const { code, data, message } = response.data;
		if (code === 200) {
			return data;
		} else if (code === 403) {
			// 未登录或登录态失效
			localStorage.clear();
			router.replace({ name: "login" });
			return;
		}
		console.log(message);
		Message.error(message);
		return Promise.reject(response.data);
	},
	(error) => {
		const { response } = error;
		switch (response.status) {
			case 401:
				localStorage.clear();
				router.replace({ name: "login" });
				break;
			default:
				Message.error(
					response.data.message || response.data.msg || "网络错误"
				);
				break;
		}
		return Promise.reject(response);
	}
);

export default axios;
